//多张图片上传
var imgArr = [];
var app = getApp().globalData;

var md5 = require("./md5.js");
import {
	store
} from "@/store/index.js";

function uploadimg(data, callback) {
	var that = this,
		index = data.i ? data.i : 0,
		//当前上传的哪张图片
		success = data.success ? data.success : 0,
		//上传成功的个数
		fail = data.fail ? data.fail : 0; //上传失败的个数

	if (index == 0) {
		uni.showLoading({
			title: '正在上传'
		});
	}

	var formData = data.formData ? data.formData : {};
	var needSign = data.needSign === false ? false : true;
	var requestUrl; //请求地址

	var userInfo = uni.getStorageSync('userInfo');
	formData.merchant_id = getApp().globalData.XcxData.merchant_id; //商户id

	if (userInfo.uid && needSign) {
		formData.uid = userInfo.uid; //用户id
	}

	if ((formData.store_id === '' || formData.store_id === undefined || formData.store_id === null) && store.store_id) {
		formData.store_id = store.store_id; //门店id
	}

	var openid = getApp().globalData.XcxData.openid;
	if (openid) {
		formData.openid = openid; //用户openid
	}
	// #ifdef MP-WEIXIN
	formData.original_type = 1;
	// #endif
	// #ifdef MP-ALIPAY
	formData.original_type = 2;
	// #endif

	requestUrl = getApp().globalData.XcxData.siteBaseUrl + data.url;

	if (getApp().globalData.XcxData.systemInfo && getApp().globalData.XcxData.systemInfo.model) {
		formData.equip = getApp().globalData.XcxData.systemInfo.model;
	}

	var key = uni.getStorageSync('signKey');

	if (key && needSign) {
		let keysSorted = Object.keys(formData).sort(); //排序健名

		var signArr = {};

		for (let j = 0; j < keysSorted.length; j++) {
			signArr[keysSorted[j]] = formData[keysSorted[j]];
		}

		formData = signArr;
	}

	var postData = formData;
	formData = getApp().globalData.modifyPostParam(formData);
	console.log(formData);

	if (key && needSign) {
		var str = formData + '&key=' + key;
		var str = decodeURIComponent(str);
		var sign = md5.md5(str);
		postData.sign = sign;
		formData += '&sign=' + sign;
	}

	console.log(requestUrl);
	console.log(postData);
	console.log(formData);
	uni.uploadFile({
		url: requestUrl,
		filePath: data.path[index],
		name: data.name,
		//这里根据自己的实际情况改
		formData: postData,
		//这里是上传图片时一起上传的数据
		method: "POST",
		success: resp => {
			console.log(resp);
			let imgobj = JSON.parse(resp.data);
			imgArr.push(imgobj[data.res_name]);
			success++; //图片上传成功，图片上传成功的变量+1
		},
		fail: res => {
			uni.showToast({
				title: '上传失败'
			});
			fail++; //图片上传失败，图片上传失败的变量+1
		},
		complete: () => {
			index++; //这个图片执行完上传后，开始上传下一张

			if (index == data.path.length && success == data.path.length) {
				//当图片传完时，停止调用          
				callback(imgArr.join(','), data.callback_data);
				imgArr = [];
				uni.hideLoading();
			} else {
				//若图片还没有传完，则继续调用函数
				data.i = index;
				data.success = success;
				data.fail = fail;
				that.uploadimg(data, callback);
			}
		}
	});
}

module.exports = {
	uploadimg: uploadimg,
};
